package com.cai.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cai.seckill.pojo.SeckillOrder;
import com.cai.seckill.mapper.SeckillOrderMapper;
import com.cai.seckill.pojo.User;
import com.cai.seckill.service.SeckillOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 秒杀订单表 服务实现类
 * </p>
 *
 * @author Uli1024
 * @since 2022-08-06
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements SeckillOrderService {
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取秒杀结果
     * orderId：成功； -1：失败； 0：排队中
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public Long getResult(User user, Long goodsId) {
        //到数据库查询订单
        //SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId())
        //        .eq("goods_id", goodsId));

        //到redis查询订单
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);

        //1.数据库中有该订单返回orderId    2.库存为空返回-1    3.否则返回0继续等待
        if (null != seckillOrder) {
            return seckillOrder.getOrderId();
        } else if (redisTemplate.hasKey("isStockEmpty:" + goodsId)) {
            return -1L;
        } else {
            //没查到结果
            //如果redis中有请求错误标记，结束用户轮询，判为秒杀失败
            Integer flag = (Integer) redisTemplate.opsForValue().get("seckillException:" + user.getId() + ":" + goodsId);
            if (null != flag) {
                return -2L;
            }
            return 0L;
        }

    }
}
